import {ConfigDataEntity} from "../../generate/entitas";
import {ExcelService} from "./ExcelService";
import {MemberHeadData} from "../MemberHeadData";
import {CellData} from "../CellData";
import exp = require("constants");

export class EntityService{
	public static mergeEntityData(exportEntity : ConfigDataEntity, oriEntity : ConfigDataEntity){
		this.mergeEntityHeadData(exportEntity, oriEntity)
		let cellList = this.mergeRowEntityData(exportEntity, oriEntity)
		this.mergeColumnEntityData(exportEntity, cellList)
	}

	public static mergeEntityHeadData(exportEntity : ConfigDataEntity, oriEntity : ConfigDataEntity){
		let full_name = oriEntity.fullName.value
		let sheet_name = oriEntity.sheetName.value
		console.log(`[解析] ${sheet_name}`)
		let headData = ExcelService.parseHeadData(oriEntity)
		let oldHeadData : Array<MemberHeadData>
		if (exportEntity.hasMemberHeadDataList()){
			oldHeadData = exportEntity.memberHeadDataList.value
			for (let i = 0; i < headData.length; i++) {
				if (!oldHeadData[i] .equal(headData[i]) ){
					console.error(`[Split] Split表格的表头不匹配, file:${full_name}, sheet_name:${sheet_name}, 不匹配的列:${i} 不匹配的数据: ${oldHeadData[i]} == ${headData[i]}`)
					process.exit(1)
				}
				oldHeadData[i].merge(headData[i])
			}
		}else{
			oldHeadData = headData
		}
		exportEntity.replaceMemberHeadDataList(oldHeadData)
	}

	public static mergeRowEntityData(exportEntity : ConfigDataEntity, oriEntity : ConfigDataEntity){
		let cellList : Array<CellData> = []
		if (exportEntity.hasRowCellList()){
			cellList = exportEntity.rowCellList.value
		}
		let oriCellList = ExcelService.parseSheetCellList(oriEntity)
		let all_list = cellList.concat(oriCellList)
		exportEntity.replaceRowCellList(all_list)
		return cellList
	}

	public static mergeColumnEntityData(exportEntity : ConfigDataEntity, cellList : Array<CellData>){
		let columnEntityList = []
		let headList = exportEntity.memberHeadDataList.value
		for (let i = 0; i < headList.length; i++) {
			let e = context.createEntity()
			e.replaceMemberHeadData(headList[i])
			e.replaceColumnIndex(i)
			e.replaceRootEntity(exportEntity)
			columnEntityList.push(e)
		}
		exportEntity.replaceColumnEntityList(columnEntityList)
	}
}